package com.rlz.framemm.util.single

import com.rlz.base.util.single.Single
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Created by RLZ
 * on 2021/10/15
 *  创建单例 示例
 */
class SimpleSingle {

    private var mUrl: String? = null
    private var mUrl1: String? = null
    private var mUrl2: String? = null
    private var mUserName: String? = null

    companion object : Single<SimpleSingle>(::SimpleSingle)

    fun getString(): String {
        return "Single create finish "
    }


    //如果一个需要判空
    fun let() {
        //error
        /*if (mUrl != null) {
            upload(mUrl)
        }*/

        //correct
        mUrl?.let { upload(it) }
    }

    private fun upload(url: String) {
        print(url)
    }


    //如果存在多个判空的需要
    fun isNonNull() {
        //error
        //通过两个let可以达到一样的效果 但是不优雅


        //定义一个函数 可以解决
        ifNotNull(mUrl1, mUrl2) { u1, _ ->
            upload(u1)
        }
    }


    private fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) {
        if (value1 != null && value2 != null) {
            bothNotNull(value1, value2)
        }
    }


    //如果希望 获取到的有默认的返回值
    fun getUserName(): String {
        //error
        /*return if (mUserName != null) {
            mUserName!!
        } else {
            "我是名字"
        }*/

        //correct
        return mUserName ?: "我是名字"
    }


    fun execute() {
        print("Start")
        GlobalScope.launch {
            delay(2000)
            print("Hello")
        }

        print("End")
    }
}